<?php defined('SYSPATH') or die('No direct script access.');

class Model_Shop extends ORM
{  
    protected $_reload_on_wakeup = false;
    
    protected static function _compare($a, $b)
    {
        return $a['count'] < $b['count'];
    }
    
    public function get_shops($coupons)
    {
        $shops = array();
        $ids   = array();
        foreach ($coupons as $coupon) {
            $ids[$coupon->shop_id] = $coupon->shop_id;    
        }
        
        $shops = array();
        $tmp_shops = ORM::factory('shop')
                        ->where('id', 'IN', $ids)
                        ->find_all()
                        ->as_array();
        foreach ($tmp_shops as $shop) {
            $shops[$shop->id] = $shop;           
        } 
        
        return $shops;                                         
    }
    
    public function get_shop_by_url($url)
    {
        return ORM::factory('shop')->where('url', '=', $url)->find();    
    }
    
    public function get_top_shops()
    {
        if ($shops = Cache::instance()->get('top_shops')) {
            return $shops;
        }
        
        $date = new DateTime();        
        $shops = DB::select('*', array(DB::expr('(SELECT COUNT(*) FROM coupons WHERE shop_id = shops.id AND end_date > \''.$date->format('Y-m-d H:i:s').'\')'), 'count'))
                    ->from('shops')
                    ->order_by('count', 'DESC')
                    ->limit(20)
                    ->execute()
                    ->as_array();
        Cache::instance()->set('top_shops', $shops);             
        return $shops;   
    }
    
    public function get_all_shops()
    {
        if ($shops = Cache::instance()->get('all_shops')) {
            return $shops;
        }
        
        $shops = DB::select('*', array(DB::expr('(SELECT COUNT(*) FROM coupons WHERE shop_id = shops.id)'), 'count'))
                    ->from('shops')
                    ->order_by('count', 'DESC')
                    ->execute()
                    ->as_array();
                     
        Cache::instance()->set('all_shops', $shops);             
        return $shops;   
    }
    
}